<template>
  <div class="drag-container">
    <div draggable="true"
      v-for="(item, index) in items" 
      :key="item.id"
      class="drag-item-wrapper"
    >
      <DragItem
        :item="item"
        @delete="handleDelete(index)"
        @update="handleUpdate(index, $event)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import DragItem from './DragItem.vue'
import Sortable from 'sortablejs'

interface DragItemData {
  id: string
  x: number
  y: number
  width: number
  height: number
  content: string
}

const items = ref<DragItemData[]>([
  { id: '1', x: 0, y: 0, width: 100, height: 100, content: 'Item 1' },
  { id: '2', x: 120, y: 0, width: 100, height: 100, content: 'Item 2' },
  { id: '3', x: 240, y: 0, width: 100, height: 100, content: 'Item 3' }
])

const handleDelete = (index: number) => {
  items.value.splice(index, 1)
}

const handleUpdate = (index: number, newItem: DragItemData) => {
  items.value[index] = newItem
}

const initSortable = () => {
  const container = document.querySelector('.drag-container')
  if (container) {
    Sortable.create(container, {
      animation: 150,
      ghostClass: 'sortable-ghost',
      onEnd: (evt) => {
        const item = items.value[evt.oldIndex!]
        items.value.splice(evt.oldIndex!, 1)
        items.value.splice(evt.newIndex!, 0, item)
      }
    })
  }
}

initSortable()

defineExpose({
  items
})
</script>

<style scoped>
.drag-container {
  position: relative;
  width: 100%;
  height: 500px;
  border: 1px dashed #ccc;
  padding: 10px;
}

.drag-item-wrapper {
  display: inline-block;
  margin: 5px;
}

.sortable-ghost {
  opacity: 0.5;
}
</style>